angular.module('myApp.directive.login', [])

    .directive('login', function () {
        return {
            restrict: 'EA',
            replace: true,
            templateUrl: 'components/login/login.html',
            controller: function ($scope, $http, $CONST, $user, api, $location, $rootScope) {
                $scope.codeUrl = '';

                // 用户登录需要的数据
                $scope.loginInfo = {
                    user_phone: '',
                    user_pass: '',
                    verification: '',
                    version_type: 0,
                    noValidate: true
                };

                /**
                 * 调用登录接口
                 */
                $scope.toLogin = function () {
                    // 校验图片验证码
                    api.apiCheckImageCode($scope.codeStr, $scope.loginInfo.verification).success(function (resp) {
                        api.apiLogin($scope.loginInfo).then(function (value) {
                            $user.setUser(value.data.data.authInfo);
                            $rootScope.isHide = false;
                            $location.path('/');
                        }, function () {
                            $scope.changeCodeImage();
                        })
                    }).error(function () {
                        $scope.changeCodeImage();
                    });
                };

                /**
                 * 改变验证码图片
                 */
                $scope.changeCodeImage = function () {
                    $scope.codeStr = Math.floor(Math.random() * 100000);
                    $scope.codeUrl = $CONST.$IP + 'system/v1/verification/' + $scope.codeStr;
                };

                // 默认加载一个验证码图片
                $scope.changeCodeImage();
            }
        };
    });
